<template>
  <div class="container">
    <van-nav-bar title="维修报工" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <!-- <van-button class="saveBtn" type="primary" native-type="submit" @click="handleSubmit()">保存</van-button> -->
    <div class="saveBtnDiv">
      <van-button class="saveBtns" type="primary" native-type="submit" @click="handleSubmit(2)">维修报工</van-button>
      <van-button class="saveBtns" style="margin-right:5px ;" type="primary" native-type="submit" @click="handleSubmit(1)">保存</van-button>
    </div>
    <div class="publicBox formDivBox">
      <van-form ref="form">
        <van-field label="设备" :value="`${ruleForm.equipName}${ruleForm.equipCode ? '【' + ruleForm.equipCode + '】' :''}`" readonly size="mini" />
        <van-field label="故障分类" :value="ruleForm.faultClassifyName" readonly size="mini" />
        <van-field label="紧急度" :value="ruleForm.emergency" readonly size="mini" />
        <van-field label="班组" :value="ruleForm.groupName" readonly size="mini" />
        <van-field label="责任人" :value="ruleForm.dutyUserName" readonly size="mini" />
        <van-field v-model="ruleForm.faultRemark" label="故障描述" readonly rows="3" size="mini" type="textarea" maxlength="200" show-word-limit />

        <van-field readonly clickable placeholder="请选择" name="repairClassifyName" v-model="ruleForm.repairClassifyName" label="维修分类" @click="showClassfy = true" :rules="[{ required: true, message: '请选择维修分类', trigger: 'blur' }]" />

        <van-field-checkbox label="维修人员" v-model="ruleForm.userLists" placeholder="请选择维修人员" :columns="userLists" :option="{label:'userName',value:'userId'}" @confirm="chooseUser($event)" />

        <van-field label="开始时间" name="startTime" :rules="[{ required: true, message: '请选择开始时间', trigger: 'blur' }]" v-model="ruleForm.startTime" size="mini" readonly @click="timeChange(1)" />

        <van-field label="结束时间" name="endTime" :rules="[{ required: true, message: '请选择结束时间', trigger: 'blur' }]" v-model="ruleForm.endTime" size="mini" readonly @click="timeChange(2)" />

        <div class="inputRightFont">
          <van-field label="*维修工时" disabled :rules="[{ required: true, message: '请输入维修工时', trigger: 'blur' }]" v-model="ruleForm.repairHours" :max="9999.99" style="width:90%; float: left;" type="number" placeholder="请输入数字" :formatter="formatter" />
          <span class="sp">分钟</span>
        </div>
        <div class="inputRightFont">
          <van-field label="*维修成本" :rules="[{ required: true, message: '请输入维修成本', trigger: 'blur' }]" v-model="ruleForm.repairCost" :max="99999999.99" style="width:93%; float: left;" type="number" placeholder="请输入数字" :formatter="formatter" />
          <span class="sp">元</span>
        </div>
        <van-field name="isSolve" label="是否解决">
          <template #input>
            <van-radio-group v-model="ruleForm.isSolve" direction="horizontal">
              <van-radio :name="1">是</van-radio>
              <van-radio :name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field v-model="ruleForm.faultAnalysis" placeholder="请输入故障分析" label="故障分析" rows="3" size="mini" type="textarea" maxlength="200" show-word-limit />
        <van-field v-model="ruleForm.repairMatters" placeholder="请输入维修事项" label="维修事项" rows="3" size="mini" type="textarea" maxlength="200" show-word-limit />
      </van-form>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
    <!-- 维修分类 -->
    <van-popup v-model="showClassfy" position="bottom">
      <van-picker title="维修分类" show-toolbar :columns="repairClassData" @confirm="onClassfy" @cancel="showClassfy = false" />
    </van-popup>
  </div>
</template>
<script>
import { myFunction, computationTime } from '@/utils/function'
import vanFieldCheckbox from '@/components/selectUser'
export default {
  name: 'RepairRequest',
  components: { vanFieldCheckbox },
  data() {
    return {
      currentDate: new Date(),
      userList: [],
      userLists: [],
      ruleForm: {
        userLists: [],
        userList: [],
        repairMatters: '',
        faultAnalysis: '',
        repairClassifyId: '',
        repairClassifyName: '',
        factoryName: '',
        repairCost: '',
        repairHours: '',
        startTime: '',
        endTime: ''
      },
      show: false,
      code: localStorage.getItem('code'),
      search: {
        current: 1,
        size: 5
      },
      list: [],
      loading: false,
      isLoading: false,
      detailsObj: {},
      showTime: false,
      showUser: false,
      showClassfy: false,
      repairClassData: [],
      repairClassDatas: [],
      nums: null
     
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler(row) {
        if (row) {
          if (computationTime(row.startTime, row.endTime) < 0) {
            row.endTime = ''
            this.$toast.fail('结束时间不能早于开始时间！')
          }
        }
      }
    }
  },
  created() {},
  mounted() {
    this.getData()
  },
  methods: {
    formatter(value) {
      return value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
    },
    async getData() {
      this.detailsObj = this.$store.state.data
      this.detailsObj.isSolve =
        this.detailsObj.isSolve === null ? 1 : this.detailsObj.isSolve
      /* 获取班组下人员 */
      await this.getGroupUsers()
      await this.getClassFy()
      setTimeout(() => {
        this.ruleForm = { ...this.ruleForm, ...this.detailsObj }
        if (this.detailsObj.repairUserId) {
          this.ruleForm.userLists = this.detailsObj.repairUserId.split(',')
        }
        if (this.detailsObj.repairClassifyId) {
          this.ruleForm.repairClassifyName = this.repairClassDatas.find(
            (item) => item.id === this.detailsObj.repairClassifyId
          ).classifyName
        }
        /* 默认为系统当前时间 */
        this.ruleForm.endTime = myFunction(new Date()).slice(0, 16)
        // 开始时间默认任务开始时间
        this.ruleForm.startTime = this.detailsObj.startTime.slice(0, 16)
        setTimeout(() => {
          const timloe =
            Date.parse(new Date()) -
            new Date(this.ruleForm.startTime.replace(/-/g, '/')).getTime()
            
          if (timloe > 0) {
            this.ruleForm.repairHours = (timloe / (1000 * 60)).toFixed(1)
          } else {
            this.ruleForm.repairHours = '0.0'
          }
        }, 100)
        console.log(this.ruleForm)
      })
    },
    /* 获取维修分类 */
    async getClassFy() {
      const res = await this.$axios.get(
        `/dobo-equip/equip/repair/classify/getList`
      )
      if (res.data.code === 200) {
        this.repairClassDatas = res.data.data
        res.data.data.forEach((item) => {
          this.repairClassData.push(item.classifyName)
        })
      }
    },
    /* 获取班组下的人员 */
    async getGroupUsers() {
      const res = await this.$axios.get(
        `/dobo-equip/repair/order/in/getGroupUser?groupId=${this.detailsObj.groupId}`
      )
      if (res.data.code === 200) {
        this.userLists = res.data.data
      }
    },
    /**  选择检验工具 */
    chooseUser(e) {
      this.userLists.forEach((item) => {
        e.forEach((itx) => {
          if (item.userId === itx) {
            this.ruleForm.userList.push(item.userId)
          }
        })
      })
    },
    /* 维修分类选择 */
    onClassfy(e) {
      this.repairClassDatas.forEach((item) => {
        if (item.classifyName === e) {
          this.ruleForm.repairClassifyId = item.id
          this.ruleForm.repairClassifyName = item.classifyName
        }
      })
      this.showClassfy = false
    },
    timeChange(num) {
      this.nums = num
      this.showTime = true
    },
    /* 时间选择赋值 */
    onTimeChange(value) {
      setTimeout(() => {
        if (this.nums === 1) {
          this.ruleForm.startTime = myFunction(value).slice(0, 16)
        } else {
          this.ruleForm.endTime = myFunction(value).slice(0, 16)
        }
        const timloe =
          new Date(this.ruleForm.endTime.replace(/-/g, '/')).getTime() -
          new Date(this.ruleForm.startTime.replace(/-/g, '/')).getTime()
        if (timloe > 0) {
          this.ruleForm.repairHours = (timloe / (1000 * 60)).toFixed(1)
        } else {
          this.ruleForm.repairHours = '0.0'
        }
        this.showTime = false
      }, 500)
    },
    handleSubmit(num) {
      this.$refs.form
        .validate()
        .then(() => {
          this.$dialog
            .confirm({
              title: '提示',
              message: '是否确认提交？'
            })
            .then(() => {
              this.submitApi(num)
            })
            .catch(() => {
              return false
            })
        })
        .catch(() => {})
    },
    submitApi(num) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      if (num === 1) {
        this.ruleForm.isReport = 0
      } else {
        this.ruleForm.isReport = 1
      }
      const list = []
      this.userLists.forEach((item) => {
        this.ruleForm.userLists.forEach((itx) => {
          if (item.userId === itx) {
            list.push({ userId: item.userId, userName: item.userName })
          }
        })
      })
      this.ruleForm.startTime = this.ruleForm.startTime + ':00'
      this.ruleForm.endTime = this.ruleForm.endTime + ':00'
      this.ruleForm.userList = list
      delete this.ruleForm.userLists
      this.$axios
        .post('/dobo-equip/repair/order/in/report', this.ruleForm)
        .then((res) => {
          if (res.data.code === 200) {
            toast.clear()
            this.$dialog
              .alert({
                title: '提示',
                message: '提交成功!'
              })
              .then(() => {
                this.$router.push('/internalRepair')
              })
              .catch(() => {})
          } else {
            this.$toast.fail(res.data.msg)
            setTimeout(() => {
              toast.clear()
              this.$router.push('/internalRepair')
            }, 1000)
          }
        })
        .catch(() => {})
    },
    // 返回
    onClickLeft() {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/internalRepair')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .saveBtnDiv {
    position: absolute;
    right: 10px;
    top: 10px;
    width: 200px;
    height: 40px;
    text-align: right;
  }
  .inputRightFont {
    overflow: hidden;
    height: 40px;
    line-height: 40px;
    .sp {
      padding-left: 5px;
    }
  }
  .formDivBox {
    .van-field {
      border: 1px solid #f5f5f5;
    }
  }
}
</style>
<style lang='scss'>
// 提交按钮样式
.saveBtnDiv {
  .saveBtns {
    float: right;
    font-size: 16px;
    z-index: 102;
    height: 40px;
    line-height: 40px;
    background: linear-gradient(to top right, #1cacff, #022566);
    border: 1px solid #022566;
    padding: 0 12px;
    .van-button__content {
      display: block;

      .van-button__text {
        text-align: center;
        width: 100%;
        font-size: 20px;
      }
    }
  }
}
</style>
